import type { IObject } from '@/types/common';
import request from '@/utils/request';
import { ElMessage } from 'element-plus'

/* post 请求 */
export function fetchDataPost(url: string, data: IObject, isToken: boolean = true) {
  return request({
    url: url,
    method: 'post',
    data: data,
    headers: isToken ? {} : { flag: 'not-login' }
  })
}

/* get 请求 */
export function fetchDataGet(url: string, data: IObject, isToken: boolean = true) {
  return request({
    url: url,
    method: 'get',
    params: data,
    headers: isToken ? {} : { flag: 'not-login' }
  })
}

//  登录
export async function login(data: IObject = {}) {
  const res: any = await request({
    url: '/login',
    method: 'post',
    headers: { flag: 'login' },
    data: data
  })

  const { code, msg } = res;

  if (code !== 200) {
    ElMessage.error(msg);
  }
}

//  获取 验证码
export async function getCaptchaImage(data: IObject = {}) {
  const res: any = await request({
    url: '/captchaImage',
    headers: { flag: 'login' },
    method: 'get',
    params: data
  });

  return res;
}

/* 文件上传 */
// export const getAllDict = () => {
//   return request({
//     url: '/dict/list/all',
//     method: 'get'
//   })
// }

//  批量请求 - 为了减少请求token次数
export async function batchFetchApi(arr: any[] = []) {
  let resultArr: any[] = [];
  let promiseArr: any = [];
  promiseArr = arr.map(_func => _func());
  //  批量请求
  resultArr = await Promise.all(promiseArr);

  const item: any = resultArr.find(_s => _s.code !== 200);

  if (item) {
    ElMessage.error(item.msg);
  }

  return resultArr;
}
